#pragma once
#include <iostream>
#include <unistd.h>
#include <string>
#include <cstring>
#include "log.hpp"
#include "err.hpp"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <cerrno>
using namespace std;
static const int gbacklog=1;



class Sock
{
public:
    void Socket()
    {
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_sock < 0)
        {
            LogMessage(Fatal, "socket error,error node:%d,error string:%s", errno, strerror(errno));
            exit(SOCKET_ERR);
        }
        int option=1;
        setsockopt(_sock,SOL_SOCKET,SO_REUSEADDR,&option,sizeof(option));
    }

    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        int n = bind(_sock, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LogMessage(Fatal, "bind error,error node:%d,error string:%s", errno, strerror(errno));
            exit(BIND_ERR);
        }
    }

    void Listen()
    {
        int n=listen(_sock,gbacklog);
        if (n < 0)
        {
            LogMessage(Fatal, "listen error,error node:%d,error string:%s", errno, strerror(errno));
            exit(LISTEN_ERR);
        }
    }


    int Accept(string& ip,uint16_t& port)
    {
        struct sockaddr_in client;
        socklen_t len=sizeof(client);
        int sock=accept(_sock,(struct sockaddr*)&client,&len);
        if (sock < 0)
        {
            LogMessage(Fatal, "accept error,error node:%d,error string:%s", errno, strerror(errno));
            exit(ACCEPT_ERR);
        }
        char buff[1024];
        ip=inet_ntoa(client.sin_addr);   
        port=ntohs(client.sin_port);
        return sock;
    }

    int Connect(const string& serverip,const uint16_t serverport)
    {
        struct sockaddr_in server;
        bzero(&server,sizeof(server));
        server.sin_addr.s_addr=inet_addr(serverip.c_str());
        server.sin_port=htons(serverport);
        server.sin_family=AF_INET;
        int n=connect(_sock,(struct sockaddr*)&server,sizeof(server));
        return n;

    }


    int GetSock()
    {
        return _sock;
    }


private:
    int _sock; // 根据调用者变化，可以是listensock，也可以是sock
};